package main

import (
	"fmt"
	"go-xorm-01/utils"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

var engine *xorm.Engine

// Get方法 : https://xorm.io/zh/docs/chapter-05/3.get/
// 查询单条数据使用Get方法，在调用Get方法时需要传入一个对应结构体的指针，同时结构体中的非空field自动成为查询的条件和前面的方法条件组合在一起查询。
func main() {
	SnakeMapper()
	//insetManyUser(engine)
	//engine.DumpAllToFile("demo05-query/demo01-querywhere/sql.sql")
	queryUser(engine)
}

func queryUser(engine *xorm.Engine) {
	user := new(UserQuery)
	total, err := engine.Where("id >?", 1).Count(user)
	if err != nil {
		fmt.Printf("err:%v", err)
	}
	fmt.Println("total=", total)
}

func SnakeMapper() {
	engine = utils.GenerateEngine()
	engine.SetMapper(names.SnakeMapper{}) // SnakeMapper 【默认】
	err := engine.Sync2(new(UserQuery))
	if err != nil {
		fmt.Printf("err:%v", err)
	}
	engine.ShowSQL(true)
	engine.SetLogLevel(log.LOG_DEBUG)

}

func insetManyUser(engine *xorm.Engine) {
	groupOne := make([]*UserQuery, 0)
	for i := 0; i < 5; i++ {
		groupOne = append(groupOne, &UserQuery{
			Username: fmt.Sprintf("zhangsan-%d", i),
			Password: fmt.Sprintf("123456-%d", i),
			GroupId:  1,
			Rank:     i,
		})
	}
	engine.Insert(groupOne)

	groupTwo := make([]*UserQuery, 0)
	for i := 0; i < 3; i++ {
		groupTwo = append(groupTwo, &UserQuery{
			Username: fmt.Sprintf("lisi-%d", i),
			Password: fmt.Sprintf("00000-%d", i),
			GroupId:  2,
			Rank:     i,
		})
	}
	engine.Insert(groupTwo)

}

type JsonTime time.Time

func (j JsonTime) MarshalJSON() ([]byte, error) {
	return []byte(`"` + time.Time(j).Format("2006-01-02 15:04:05") + `"`), nil
}

type UserQuery struct {
	Id        int64     `xorm:"pk autoincr"`                                              //指定列名 ，默认id
	Username  string    `xorm:"varchar(25) notnull unique(u_p) 'username' comment('姓名')"` //复合唯一索引
	Password  string    `xorm:"varchar(25) notnull unique(u_p) 'password' comment('密码')"` //复合唯一索引
	TimeOne   time.Time `xorm:"created"`
	TimeTwo   JsonTime  `xorm:"created"`
	TimeThree int64     `xorm:"created"`
	GroupId   int64
	Rank      int
}
